package cn.util;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

//解析request对象的所有参数，封装成一个指定数据类型对象
public class PackObject<T> {

	@SuppressWarnings("rawtypes")
	// 执行set方法，返回对象
	public static <T> T getObject(HttpServletRequest request, Class<T> c) {
		T t = null;
		try {
			t = c.newInstance(); // 实例化参数对象
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 所有请求参数
		Enumeration e = request.getParameterNames();
		// 参数对象的所有方法
		Method[] methods = c.getDeclaredMethods();
		// 根据对象的set方法的参数类型去将请求的值做相应转换
		while (e.hasMoreElements()) {
			String paramName = e.nextElement().toString();
			// 将参数名字转换成set方法名字，如：id
			String setParamName = reverseParamName(paramName);
			for (Method method : methods) {
				if (setParamName.equals(method.getName())) {
					System.out.println(method.getName());
					try {
						// 得到set方法参数类型
						Class<?> paramType = (method.getParameterTypes())[0];
						String value = request.getParameter(paramName);
						// 通过适配器将值注入进POJO里面
						adapter(t, method, paramType, value);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
		}
		return t;
	}

	// 组织set方法
	private static String reverseParamName(String paramName) {
		char firstChar = paramName.charAt(0);
		char toUpper = Character.toUpperCase(firstChar);
		String setParamName = "set" + String.valueOf(toUpper)
				+ paramName.substring(1);
		return setParamName;
	}

	// 方法的适配器，调用set方法
	private static <T> void adapter(T t, Method method, Class<?> paramType,
			String value) throws Exception {
		if (paramType == String.class) {
			method.invoke(t, value);
		} else if (paramType == Integer.class || paramType == int.class) {
			method.invoke(t, Integer.parseInt(value));
		} else if (paramType == Long.class || paramType == long.class) {
			method.invoke(t, Long.parseLong(value));
		} else if (paramType == Boolean.class || paramType == boolean.class) {
			method.invoke(t, Boolean.parseBoolean(value));
		} else if (paramType == Short.class || paramType == short.class) {
			method.invoke(t, Short.parseShort(value));
		} else if (paramType == Float.class || paramType == float.class) {
			method.invoke(t, Float.parseFloat(value));
		} else if (paramType == Double.class || paramType == double.class) {
			method.invoke(t, Double.parseDouble(value));
		} else if (paramType == Character.class || paramType == char.class) {
			char[] cs = value.toCharArray();
			if (cs.length > 1) {
				throw new IllegalArgumentException("参数长度太大");
			}
			method.invoke(t, value.toCharArray()[0]);
		} else if (paramType == Timestamp.class) {
			method.invoke(t, Timestamp.valueOf(value));
		}
	}
}
